package org.example.jiaxiao.service.impl;

import org.example.jiaxiao.entity.Account;
import org.example.jiaxiao.mapper.UserMapper;
import org.example.jiaxiao.service.RegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; // 导入事务注解

import java.util.Random; // 导入Random类

@Service
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    private UserMapper userMapper;

    // 用于生成随机数
    private static final Random random = new Random();

    @Override
    @Transactional // 添加事务注解
    public boolean register(Account account) {
        // 检查用户名是否已存在
        Account existingAccount = userMapper.selectByUsername(account.getUserName());
        if (existingAccount != null) {
            return false; // 用户名已存在，注册失败
        }

        // 生成 account_number (示例：使用当前时间戳和随机数)
        long accountNumber = System.currentTimeMillis() + random.nextInt(10000);
        account.setAccountNumber(accountNumber);

        // 如果是学员，生成 student_id
        if ("student".equals(account.getUsertype())) {
            // 简单生成一个 student_id，实际应用中需要更严谨的唯一ID生成策略
            int studentId = 1000 + random.nextInt(9000); //
            account.setStudentId(studentId);
        } else {
            // 如果不是学员，student_id 设置为 null
            account.setStudentId(null);
        }

        // 插入新账户
        int rows = userMapper.insertAccount(account);
        return rows > 0; // 插入成功返回true，否则返回false
    }
} 